package cn.zf233.xcloud.task;

import cn.zf233.xcloud.commom.Const;
import cn.zf233.xcloud.commom.R;
import cn.zf233.xcloud.config.lockpool.IXCloudThreadPool;
import cn.zf233.xcloud.service.AdminService;
import cn.zf233.xcloud.service.FileService;
import cn.zf233.xcloud.service.SearchService;
import cn.zf233.xcloud.service.UserService;
import cn.zf233.xcloud.util.RedisUtil;
import cn.zf233.xcloud.util.RequestCounter;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.locks.Lock;

/**
 * Created by zf233 on 2020/11/4
 * XCloud 定时任务
 */
@Component
public class XcloudSystemTimingTask {

    private final Logger logger = LoggerFactory.getLogger(XcloudSystemTimingTask.class);

    @Resource
    private IXCloudThreadPool<Lock> lockPool;

    @Resource
    private FileService fileService;

    @Resource
    private UserService userService;

    @Resource
    private AdminService adminService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SearchService searchService;

    @Scheduled(cron = "0 0 0 * * ?")
    public void requestCountLogging() {

        // 记录当天请求数量(单个服务器结点)
        logger.info("#####################################################################");
        logger.info(" ********TIMING TASK******* REQUEST COUNT ---------------> " + RequestCounter.getInstance().getRequestCount());
        logger.info(" ********TIMING TASK******* REQUEST SUCCESS -------------> " + RequestCounter.getInstance().getRequestSuccessCount());
        logger.info(" ********TIMING TASK******* REQUEST FAILURE -------------> " + RequestCounter.getInstance().getRequestFailureCount());
        logger.info("#####################################################################");

        // 重置当天请求数量(单个服务器结点)
        RequestCounter.getInstance().reset();
    }

    @Scheduled(cron = "0 20 1 * * ?")
    @SchedulerLock(name = "xcloudDataRefactoring", lockAtMostFor = "PT30M", lockAtLeastFor = "PT30M")
    public void xcloudDataRefactoring() {

        logger.info("#####################################################################");
        logger.info(" ********TIMING TASK******* FLUSH USERINFO --------------> start");

        // 清除未成功持久化的记录（oss不存在持久化文件的记录（文件）、父级文件夹不存在的文件记录（文件、文件夹））
        fileService.removeWildFile();

        R response = fileService.flushTimeoutRecycle();
        if (response.isSuccess()) {
            logger.info(" ********TIMING TASK******* FLUSH TIMEOUT RECYCLE Y------> " + response.getMsg());
        } else {
            logger.info(" ********TIMING TASK******* FLUSH TIMEOUT RECYCLE N------> " + response.getMsg());
        }

        // 移除邮箱未验证用户和从未登陆成功过的手机用户
        // userService.removeUserInfoOfRegistFailTask(false);

        // 刷新用户等级相关信息
        userService.refreshUserLevelTask();

        // 重置流量统计
        adminService.flushWeekFlow();

        // 清空Redis缓存（local redis and shared redis）
        this.clearRedis();

        // 重置锁池
        lockPool.reset();

        // 重建索引
        try {
            searchService.clearIndex();
            searchService.buildIndex();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(" ****ES INDEX CONTROL**** EXCEPTION BUILD INDEX  --------> " + e.getMessage());
        }
        logger.info(" ********TIMING TASK******* FLUSH USERINFO --------------> end");
        logger.info("#####################################################################");
    }

    public void clearRedis() {
        redisUtil.remove(Const.USER_LOGIN_FLAG_BIT_SET_KEY);
        Set<String> keys = redisUtil.keys("file*");
        keys.forEach(key -> redisUtil.remove(key));
    }
}